//
//  HXCycleImages.m
//  16_UICollectionViewCycleImage
//
//  Created by 徐昊 on 16/8/4.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "HXCycleImages.h"

#define kCollectionViewCellName @"reuse"
#define kRandomColor [UIColor colorWithRed:arc4random() % 256 / 255.f green:arc4random() % 256 / 255.f blue:arc4random() % 256 / 255.f alpha:1]
@interface HXCycleImages ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UICollectionView *cycleCollectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation HXCycleImages
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
//        [self setUp];
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setUp];
    }
    return self;
}
- (void)setUp {
    [self createCollectionView];
    [self createPageControl];
    [self addTimer];
}
- (void)createCollectionView {
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _cycleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    _cycleCollectionView.pagingEnabled = YES;
    _cycleCollectionView.delegate = self;
    _cycleCollectionView.dataSource = self;
    _cycleCollectionView.showsHorizontalScrollIndicator = NO;
    [_cycleCollectionView registerClass:[HXCycleImagesCell class] forCellWithReuseIdentifier:kCollectionViewCellName];
    [self addSubview:_cycleCollectionView];
    
}
- (void)createPageControl {
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    [self addSubview:_pageControl];
    [_pageControl addTarget:self action:@selector(pageChange:) forControlEvents:UIControlEventValueChanged];
}
- (void)pageChange:(UIPageControl *)page {
//    [_cycleCollectionView setContentOffset:CGPointMake((page.currentPage + 1) * _cycleCollectionView.bounds.size.width, 0)];
    [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:page.currentPage + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}
- (void)addTimer {
    // 仅仅是创建, 并没有加载到loop中
//    self.timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    // 创建一个timer, 并添加到loop中
    self.timer =  [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    // NSRunLoopCommonModes 和 NSDefaultRunLoopMode
    // 后者代表多种状态, scheduledTimerWithTimeInterval添加为默认
    // 前者为多种状态, 包含 默认 及 滚动
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)nextImage {
    NSInteger page = self.pageControl.currentPage;
    if (self.pageControl.currentPage == _array.count - 3) {
        page = 0;
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:page + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else {
        page++;
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:page + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
//    self.cycleCollectionView.contentOffset = CGPointMake((page + 1) * _cycleCollectionView.bounds.size.width, 0);
//    [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:page + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    self.pageControl.currentPage = page;

}
- (void)closeTimer {
    // 取消timer时, 将timer置空
    [self.timer invalidate];
    _timer = nil;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self closeTimer];
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    [self addTimer];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _array.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    _cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellName forIndexPath:indexPath];
    _cell.cycleImage.image = [UIImage imageNamed:[_array objectAtIndex:indexPath.row]];
    return _cell;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    _cycleCollectionView.frame = self.bounds;
    _flowLayout.itemSize = self.bounds.size;
    [_cycleCollectionView setContentOffset:CGPointMake(self.bounds.size.width, 0)];
    _pageControl.frame = CGRectMake(0, 0, self.bounds.size.width / 3, 10);
    _pageControl.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height - 10);
    _pageControl.numberOfPages = 5;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger page = _cycleCollectionView.contentOffset.x / self.bounds.size.width;
    _pageControl.currentPage = page - 1;
    // 直接判断与0相等有什么问题?
    if (scrollView.contentOffset.x == 0) {
//        [_cycleCollectionView setContentOffset:CGPointMake((_array.count - 2) * _cycleCollectionView.bounds.size.width, 0)];
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_array.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        _pageControl.currentPage = _array.count - 3;
    } else if (scrollView.contentOffset.x == (_array.count - 1) * _cycleCollectionView.bounds.size.width) {
//        [_cycleCollectionView setContentOffset:CGPointMake(_cycleCollectionView.bounds.size.width, 0)];
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        _pageControl.currentPage = 0;
    }
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.datasource cycleView:self];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.delegate currentCell:_cell index:indexPath];
    }
- (void)setArray:(NSArray *)array {
    _array = array;
    [_cycleCollectionView reloadData];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

@implementation HXCycleImagesCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        _label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.bounds) / 2 - 50, 0, 100, 50)];
        _label.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:_cycleImage];
        [self.contentView addSubview:_label];
    }
    return self;
}

@end
